from database import db
from ..models.shop_cart import CartItem



class CartItemService(object):

    @classmethod
    def get_cart_item_by_source(cls, source):
        return CartItem.query.filter(
            CartItem.source == source
        ).filter(
            CartItem.status == CartItem.STATUS_NORMAL
        ).all()

    @classmethod
    def get_cart_count_by_source(cls, source):
        return CartItem.query.filter(CartItem.source == source) \
            .filter(CartItem.status == CartItem.STATUS_NORMAL) \
            .count()

    @classmethod
    def get_item_by_id(cls,id):
        return CartItem.query.filter(CartItem.id == id) \
            .filter(CartItem.status != CartItem.STATUE_REMOVED) \
            .first()

    @classmethod
    def update_item_count(cls, id, count):
        return db.session.query(CartItem).filter(CartItem.id == id) \
            .filter(CartItem.status != CartItem.STATUE_REMOVED) \
            .update(
                    {
                        CartItem.count:count
                    }
                )

    @classmethod
    def update_item(cls, item):
        if not item.id:
            db.session.add(item)
        # db.session.save(item)
        db.session.commit()

    @classmethod
    def delete_item(cls,id):
        return db.session.query(CartItem).filter(CartItem.id == id) \
            .update(
                {
                    CartItem.status:CartItem.STATUE_REMOVED
                }
            )